package com.alipay.util;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import java.io.Reader;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XMLDom4jUtils {
	 /**缺省字符集*/
	  public static final String DEFAULT_ENCODING = "GBK";
	  // Static --------------------------------------------------------
	  private static final Logger log = Logger.getLogger(XMLDom4jUtils.class);

	  /**私有构造函数，阻止非法调用构造函数*/
	  private XMLDom4jUtils() {
	  }
	  
	  /**
	   * 通过Reader读取Document文档
	   * 如果encodingStr为null或是""，那么采用缺省编码GB2312
	   * @param in Reader器
	   * @param encoding 编码器
	   * @return documment
	   * @throws Exception
	   */
	  public static Document fromXML(Reader in, String encoding) throws Exception {
	    try {
	      if (encoding == null || encoding.equals("")) {
	        encoding = DEFAULT_ENCODING;
	      }
	      SAXReader reader = new SAXReader();
	      InputSource source = new InputSource(in);
		  source.setEncoding(encoding);
		  Document document  = reader.read(source);
//		  if (document.getXMLEncoding() == null)
//			document.setXMLEncoding(encoding);
	      return document;
	    }
	    catch (Exception ex) {
	      throw new Exception(ex);
	    }
	  }

	  /**
	   * 直接从字符串得到XML的Document
	   * @param source 把一个字符串文本转化为XML的Document对象
	   * @param encoding 编码器
	   * @return <code>Document</code>
	   * @throws Exception
	   */
	  public static Document fromXML(String source, String encoding) throws
	      Exception {
        return fromXML(new StringReader(source), encoding);
	  }
	  
	  /**
		 * 解析第一层级子节点
		 * 将结果扔进map集合，方便操作
		 */
		public  static Map<String,String> getfirstChirld(Element firstChirldEl) throws Exception{
			Map<String,String> firstChirldMap = new HashMap<String,String>();
			List childrenList = firstChirldEl.elements();
			for(int i = 0;i < childrenList.size(); i++){
				Element el = (Element)childrenList.get(i);
				String name = el.getName();
				String val = el.getText();
				firstChirldMap.put(name, val);
			}
			return firstChirldMap;
		}
		
		  /**
				 * 消息解析入口方法
				 * @param req 请求字符串
				 * @return 请求数据MAP
				 * @throws Exception
				 */
		public static Map<String,String> analyzeXmlChildInfo(String req) throws Exception{
					Document requestDoc;
					requestDoc = XMLDom4jUtils.fromXML(req, XMLDom4jUtils.DEFAULT_ENCODING);
					Element root = requestDoc.getRootElement();
					Map<String,String> childMap = XMLDom4jUtils.getfirstChirld(root);
					return childMap;
		}
		
		
		
}
